package com.hb.commons;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;
import java.util.Objects;

/**
 * 数据库实体父类
 *
 * @author zhaojk
 */
@Getter
@Setter
@ToString
public abstract class CommonEntity extends PageEntity {

    private Long id;

    /**
     * 创建日期
     */
    private Date createTime;

    /**
     * 创建人ID
     */
    private Long createId;

    /**
     * 创建人名称
     */
    private String createName;

    /**
     * 修改日期
     */
    private Date updateTime;

    /**
     * 修改人ID
     */
    private Long updateId;

    /**
     * 修改人名称
     */
    private String updateName;

    /**
     * 删除标志(0: 有效, 1: 已删除)
     */
    private Integer deleteFlag;

    /**
     * 填充基础数据
     * 填充包含属性:id, createDate, updateDate, createName, updateName, deleteFlag
     *
     * @param type 1: 新增需要的数据, 2: 修改需要的数据, 3: 删除
     * @param name 当前登陆的用户姓名
     */
    public void buildBaseData(int type, String name, Long operateId) {
        switch (type) {
            case 1:
                this.setId(ID());
                this.setCreateTime(DateUtil.date());
                this.setCreateName(name);
                this.setCreateId(operateId);
                this.setDeleteFlag(0);
                break;
            case 3:
                this.setDeleteFlag(1);
            case 2:
                this.setUpdateTime(DateUtil.date());
                this.setUpdateId(operateId);
                this.setUpdateName(name);
                break;
            default:
        }
    }

    public void buildBaseData(int type, String name) {
        buildBaseData(type, name, null);
    }

    public void buildBaseData(int type) {
        String realName = "UNKNOWN_NAME";
        buildBaseData(type, realName);
    }

    /**
     * 根据当前对象中是否拥有id属性判断设置基础数据
     *
     * @param name 当前登陆的用户姓名
     */
    public void buildBaseData(String name) {
        if (this.id == null) {
            buildBaseData(1, name);
            return;
        }
        buildBaseData(2, name);
    }

    /**
     * 将当前父类对象转换为相应的子类对象
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T extends CommonEntity> T to(Class<T> cls) {
        T childEntity = ReflectUtil.newInstanceIfPossible(cls);
        BeanUtil.copyProperties(this, childEntity);
        return childEntity;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CommonEntity that = (CommonEntity) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    /**
     * 生成主键
     *
     * @return
     */
    private static Long ID() {
        return IdUtil.getSnowflake(1, 1).nextId();
    }
}
